package models

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/qiniu/api.v7/auth/qbox"
	"github.com/qiniu/api.v7/storage"
	"os"
)

type Attach struct {
	Id         int64  `json:"id"`
	Type       int64  `json:"type"`
	Name       string `json:"name"`
	Ext        string `json:"ext"`
	Size       int    `json:"size"`
	SaveType   int8   `json:"save_type"`
	QnKey      string `json:"qn_key"`
	Path       string `json:"path"`
	CreateTime int    `json:"create_time"`
}

//图片查询参数
type AttachQueryParam struct {
	BaseQueryParam
	Type int64 `json:"type"`
}

//图片移动参数
type MoveAttachToTypeParam struct {
	Ids  []int64 `json:"attachList"`
	Type int64   `json:"typeId"`
}

type DelAttachParam struct {
	Ids []int64 `json:"id"`
}

type QiniuUploadData struct {
	Key  string `json:"key"`
	Type int64  `json:"type"`
}

//图片列表
func AttachList(params *AttachQueryParam) ([]*Attach, int64) {
	sortorder := "-Id"
	query := orm.NewOrm().QueryTable("tp_attach")
	data := make([]*Attach, 0)
	if params.Type > 0 {
		query = query.Filter("type", params.Type)
	} else {
		query = query.Filter("type", 0)
	}
	total, _ := query.Count()
	_, _ = query.OrderBy(sortorder).Limit(params.Size, (params.Page-1)*params.Size).All(&data)
	return data, total
}

//保存图片信息
func SaveAttach(m *Attach) (int64, error) {
	o := orm.NewOrm()
	if m.Id == 0 {
		id, err := o.Insert(m)
		if err != nil {
			return 0, err
		} else {
			m.Id = id
		}
	} else {
		if _, err := o.Update(m); err != nil {
			return 0, err
		}
	}
	return m.Id, nil
}

// 把图片移动到其他分类下
func MoveAttachToType(params *MoveAttachToTypeParam) (int64, error) {
	o := orm.NewOrm()
	err := o.Begin()
	query := o.QueryTable("tp_attach")
	num, err := query.Filter("id__in", params.Ids).Update(orm.Params{
		"type": params.Type,
	})
	if err != nil {
		err = o.Rollback()
	} else {
		err = o.Commit()
	}
	return num, err
}

// 删除图片
func DelAttach(params *DelAttachParam) (int64, error) {
	o := orm.NewOrm()
	maps := []Attach{}
	err := o.Begin()
	query := o.QueryTable("tp_attach")
	_, _ = query.Filter("id__in", params.Ids).All(&maps)
	num, err := query.Filter("id__in", params.Ids).Delete()
	if err != nil {
		err = o.Rollback()
	} else {
		err = o.Commit()
		AccessKey := beego.AppConfig.String("qiniu::AccessKey")
		SecretKey := beego.AppConfig.String("qiniu::SecretKey")
		Bucket := beego.AppConfig.String("qiniu::Bucket")
		mac := qbox.NewMac(AccessKey, SecretKey)
		cfg := storage.Config{
			// 是否使用https域名进行资源管理
			UseHTTPS: false,
		}
		// 指定空间所在的区域，如果不指定将自动探测
		// 如果没有特殊需求，默认不需要指定
		//cfg.Zone=&storage.ZoneHuabei
		bucketManager := storage.NewBucketManager(mac, &cfg)

		for _, item := range maps {
			if item.SaveType == 1 {
				_ = os.Remove(item.Path)
			} else {
				_ = bucketManager.Delete(Bucket, item.QnKey)
			}
		}
	}
	return num, err
}
